package com.csvvip.cloud.lb;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Component
public class MyBalancer implements LoadBalancer{

    private volatile AtomicInteger atomicInteger;


    @Override
    public ServiceInstance getBalancer(List<ServiceInstance> serviceInstance) {
        int index = getAndIncrement()%serviceInstance.size();
        return serviceInstance.get(index);
    }

    //获取下一个
    private Integer getAndIncrement(){
        int current;
        int next;
        do{
            if(this.atomicInteger == null){
                this.atomicInteger = new AtomicInteger(0);
            }
            current = this.atomicInteger.get();
            next = current >= Integer.MAX_VALUE ? 0 : current + 1 ;
        }while (!atomicInteger.compareAndSet(current , next)) ;
        System.out.println("****当前next ：" + next);
        return next;
    }
}
